package com.tz.farm_feeding.controller;

import java.util.Date;
import java.util.List;

 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.tz.farm_feeding.domain.Feed;
import com.tz.farm_feeding.domain.FeedExample;
 
import com.tz.farm_feeding.domain.status;
import com.tz.farm_feeding.mapper.FeedMapper;
import com.tz.farm_feeding.mapper.PigMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

@RestController
@RequestMapping("/feed")
public class FeedController {

  @Autowired
  FeedMapper feedMapper;
  @PostMapping(value = "/getAllFeed")
  public String getAllPig(@RequestBody JSONObject jsonparm, HttpServletRequest request, HttpSession session) {
    JSONObject resp = new JSONObject();
    List<Feed> feeds = feedMapper.selectByExample(new FeedExample());
    JSONArray jsonArray = new JSONArray();
    for (Feed fed : feeds) {
      jsonArray.add(JSONObject.parse(fed.toString()));
    }
    resp.put("result", status.s_ok);
    resp.put("data", jsonArray);

    return resp.toJSONString();
  }


  @PostMapping(value = "/addFeed")
  public String addFeed(@RequestBody JSONObject jsonparm, HttpServletRequest request, HttpSession session) {
    JSONObject resp = new JSONObject();
    String idsn = jsonparm.getString("idsn");
    int remain = jsonparm.getInteger("remain");
    int total = jsonparm.getInteger("total");
    Double cost = jsonparm.getDouble("cost");
    Feed feed = new Feed();
    feed.setIdsn(idsn);
    feed.setRemain(remain);
    feed.setTotal(total);
    feed.setCost(cost);
    feed.setCreatedate(new Date());
    feedMapper.insert(feed);
    resp.put("result", status.s_ok);
    return resp.toJSONString();
  }

 
  @PostMapping(value = "/eatFeed")
  public String eatFeed(@RequestBody JSONObject jsonparm, HttpServletRequest request, HttpSession session) {
    JSONObject resp = new JSONObject();
    int remain = jsonparm.getInteger("remain");
    int id = jsonparm.getInteger("id");
    FeedExample feedExample = new FeedExample();
    FeedExample.Criteria criteria= feedExample.createCriteria();
    criteria.andIdEqualTo(id);
    Feed feed = new Feed();
    feed.setRemain(remain);
    feedMapper.updateByExampleSelective(feed, feedExample);
    resp.put("result", status.s_ok);
    return resp.toJSONString();
  }
}

